package org.sharkness.jsf.support;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;

import org.sharkness.business.entity.Model;
import org.sharkness.business.factory.ModelFactory;
import org.sharkness.business.support.ModelService;
import org.sharkness.web.component.ConverterComponent;
import org.springframework.web.jsf.FacesContextUtils;

@SuppressWarnings("serial")
public class ModelConverter<T, Service extends ModelService<T>> implements ConverterComponent {

	Class<Service> modelService;
	
	public ModelConverter() {
		try {
			this.modelService = ModelFactory.getClass(this);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public Object getAsObject(FacesContext fc, UIComponent ui, String s) {
		try {
			long id = Long.parseLong(s);
			ModelService<T> modelService = FacesContextUtils
					.getWebApplicationContext(fc).getBean(this.modelService);
			return modelService.getById(id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public String getAsString(FacesContext fc, UIComponent ui, Object o) {
		return Long.toString(((Model)o).getId());
	}

}